package openase.audiosearch.job;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ConnectionAcceptJob extends Job {

	private static final Log logger = LogFactory.getLog(ConnectionAcceptJob.class);

	public ConnectionAcceptJob(SelectionKey sk) {
		super(sk);
	}

	public void run() {
		SelectionKey key = key();

		ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
		SocketChannel clientChannel = null;
		try {
			clientChannel = ssc.accept();
			if (clientChannel == null) {
				return;
			}
			logger.info("New connection request received: " + clientChannel.socket().getInetAddress());

			// clientChannel.socket().setSoTimeout(2000);
			// clientChannel.socket().setSoLinger(false, 0);
			// clientChannel.socket().setTcpNoDelay(true);
			clientChannel.configureBlocking(false);

			while (!clientChannel.finishConnect()) {
				sleep(200);
			}

			clientChannel.register(key.selector(), SelectionKey.OP_READ);

			logger.info("Connection established: " + clientChannel.socket().getInetAddress());
		} catch (IOException ioe) {
			logger.error("I/O error during connection acceptance", ioe);
			IOUtils.closeQuietly(clientChannel);
		}
	}

	private void sleep(long timeInMillis) {
		try {
			Thread.sleep(timeInMillis);
		} catch (InterruptedException e) {
			// ignore
		}
	}

}
